<template>
    <div class="title_tab">
        <ul class="my_ul" style="height: 40px;" ref="myUl">
            <li v-for="(item, index) in tabArr" :key='index' @click="changeTab($event, index)">{{ item }} </li>
        </ul>
        <span class="underline" :style="underlineStyle">{{ tabArr[tabIndex] }}</span>
    </div>
</template>

<script>
export default {
    name: "TabMenu",
    props: ["tabArr"],
    data() {
        return {
            tabIndex: 0,
            underlineStyle: {
                left: `0px`
            }
        };
    },
    methods: {
        /**
         * 改变tab
         * @param {HtmlElement} $e 事件对象
         * @param {Number} index 元素的索引
         */
        changeTab($e, index) {
            // 改变underline的内容
            this.tabIndex = index;
            // // 方式1：根据index计算left
            // let $liList = this.$refs.myUl.children;
            // let left = 0;
            // for (let item of $liList) {
            //     if (item === $e.target) {
            //         this.underlineStyle.left = `${left}px`;
            //         break;
            //     }
            //     left += item.offsetWidth;
            // }

            // 方式2
            this.underlineStyle.left = `${$e.target.offsetLeft}px`
            this.$emit("changeTab", index);
        }
    }
};
</script>

<style lang="scss">
.title_tab {
    width: 100%;
    position: relative;
    line-height: 16px;

    li {
        width: 165px;
        height: 38px;
        text-align: center;
        list-style: none;
        float: left;
        font-size: 16px;
        line-height: 40px;
        border-bottom: 1px solid #e5e5e5;
        overflow: visible;
        cursor: pointer;
    }

    .li_choosed {
        color: #3f9f5f;
    }

    .underline {
        position: absolute;
        width: 165px;
        height: 100%;
        line-height: 30px;
        border-bottom: 2px solid #28b76c;
        bottom: 1px;
        color: hsla(0, 0%, 100%, 0);
        font-size: 18px;
        cursor: pointer;
        transition: left 0.2s linear;
    }
}
</style>